<?php

namespace app\common\library;

use app\common\model\User;
use app\admin\model\Admin as AdminModel;
use think\Db;
use think\Exception;

/**
 * 微信服务类
 */
class WechatService
{
    /**
     * 获取小程序配置
     */
    public static function getMiniprogramConfig()
    {
        return [
            'appid' => config('wechat.miniprogram.appid'),
            'secret' => config('wechat.miniprogram.secret'),
        ];
    }

    /**
     * 获取微信用户信息
     */
    public static function getWechatUserInfo($code)
    {
        $config = self::getMiniprogramConfig();
        
        $url = "https://api.weixin.qq.com/sns/jscode2session";
        $params = [
            'appid' => $config['appid'],
            'secret' => $config['secret'],
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ];
        
        $url .= '?' . http_build_query($params);
        $result = file_get_contents($url);
        $data = json_decode($result, true);
        
        if (isset($data['errcode'])) {
            throw new Exception('微信授权失败：' . $data['errmsg']);
        }
        
        return $data;
    }

    /**
     * 查找或创建微信用户
     */
    public static function findOrCreateWechatUser($openid, $unionid = '', $userInfo = [])
    {
        // 先查找是否已有绑定
        $user = User::where('wechat_openid', $openid)->find();
        
        if ($user) {
            return $user;
        }
        
        // 如果没有绑定，根据配置决定是否自动创建用户
        if (config('wechat.bind.auto_create_user', true)) {
            return self::createWechatUser($openid, $unionid, $userInfo);
        }
        
        return null;
    }

    /**
     * 创建微信用户
     */
    public static function createWechatUser($openid, $unionid = '', $userInfo = [])
    {
        $userData = [
            'group_id' => 1, // 默认用户组
            'username' => 'wx_' . substr($openid, -8),
            'nickname' => $userInfo['nickName'] ?? '微信用户',
            'password' => '', // 微信用户不需要密码
            'salt' => '',
            'email' => '',
            'mobile' => '',
            'avatar' => $userInfo['avatarUrl'] ?? '',
            'wechat_openid' => $openid,
            'wechat_unionid' => $unionid,
            'wechat_nickname' => $userInfo['nickName'] ?? '',
            'wechat_avatar' => $userInfo['avatarUrl'] ?? '',
            'bind_time' => time(),
            'bind_status' => 1,
            'status' => 'normal',
            'createtime' => time(),
            'updatetime' => time()
        ];
        
        return User::create($userData);
    }

    /**
     * 绑定现有用户到微信
     */
    public static function bindUserToWechat($userId, $openid, $unionid = '', $userInfo = [])
    {
        $user = User::find($userId);
        if (!$user) {
            throw new Exception('用户不存在');
        }
        
        // 检查是否已绑定
        if (!empty($user->wechat_openid)) {
            throw new Exception('该用户已绑定微信账号');
        }
        
        // 检查微信是否已被其他用户绑定
        $existingBind = User::where('wechat_openid', $openid)->find();
        if ($existingBind) {
            throw new Exception('该微信账号已被其他用户绑定');
        }
        
        Db::startTrans();
        try {
            // 更新用户信息
            $user->wechat_openid = $openid;
            $user->wechat_unionid = $unionid;
            $user->wechat_nickname = $userInfo['nickName'] ?? '';
            $user->wechat_avatar = $userInfo['avatarUrl'] ?? '';
            $user->bind_time = time();
            $user->bind_status = 1;
            
            // 如果用户昵称或头像为空，使用微信信息
            if (empty($user->nickname) || $user->nickname === $user->username) {
                $user->nickname = $userInfo['nickName'] ?? $user->nickname;
            }
            if (empty($user->avatar)) {
                $user->avatar = $userInfo['avatarUrl'] ?? $user->avatar;
            }
            
            $user->save();
            
            // 记录绑定日志
            self::logBindAction($userId, null, $openid, $unionid, 'user', 'bind', '绑定成功');
            
            Db::commit();
            return $user;
            
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 绑定管理员到微信
     */
    public static function bindAdminToWechat($adminId, $openid, $unionid = '', $userInfo = [])
    {
        $admin = AdminModel::find($adminId);
        if (!$admin) {
            throw new Exception('管理员不存在');
        }
        
        // 检查是否已绑定
        if (!empty($admin->wechat_openid)) {
            throw new Exception('该管理员已绑定微信账号');
        }
        
        // 检查微信是否已被其他管理员绑定
        $existingBind = AdminModel::where('wechat_openid', $openid)->find();
        if ($existingBind) {
            throw new Exception('该微信账号已被其他管理员绑定');
        }
        
        Db::startTrans();
        try {
            // 更新管理员信息
            $admin->wechat_openid = $openid;
            $admin->wechat_unionid = $unionid;
            $admin->wechat_nickname = $userInfo['nickName'] ?? '';
            $admin->wechat_avatar = $userInfo['avatarUrl'] ?? '';
            $admin->bind_time = time();
            $admin->bind_status = 1;
            
            // 如果管理员昵称或头像为空，使用微信信息
            if (empty($admin->nickname) || $admin->nickname === $admin->username) {
                $admin->nickname = $userInfo['nickName'] ?? $admin->nickname;
            }
            if (empty($admin->avatar)) {
                $admin->avatar = $userInfo['avatarUrl'] ?? $admin->avatar;
            }
            
            $admin->save();
            
            // 记录绑定日志
            self::logBindAction(null, $adminId, $openid, $unionid, 'admin', 'bind', '绑定成功');
            
            Db::commit();
            return $admin;
            
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 解除微信绑定
     */
    public static function unbindWechat($userId = null, $adminId = null)
    {
        if ($userId) {
            $user = User::find($userId);
            if (!$user) {
                throw new Exception('用户不存在');
            }
            
            $openid = $user->wechat_openid;
            $unionid = $user->wechat_unionid;
            
            $user->wechat_openid = '';
            $user->wechat_unionid = '';
            $user->wechat_nickname = '';
            $user->wechat_avatar = '';
            $user->bind_time = null;
            $user->bind_status = 0;
            $user->save();
            
            self::logBindAction($userId, null, $openid, $unionid, 'user', 'unbind', '解除绑定成功');
            
        } elseif ($adminId) {
            $admin = AdminModel::find($adminId);
            if (!$admin) {
                throw new Exception('管理员不存在');
            }
            
            $openid = $admin->wechat_openid;
            $unionid = $admin->wechat_unionid;
            
            $admin->wechat_openid = '';
            $admin->wechat_unionid = '';
            $admin->wechat_nickname = '';
            $admin->wechat_avatar = '';
            $admin->bind_time = null;
            $admin->bind_status = 0;
            $admin->save();
            
            self::logBindAction(null, $adminId, $openid, $unionid, 'admin', 'unbind', '解除绑定成功');
        }
    }

    /**
     * 记录绑定操作日志
     */
    public static function logBindAction($userId, $adminId, $openid, $unionid, $bindType, $action, $message)
    {
        $logData = [
            'user_id' => $userId,
            'admin_id' => $adminId,
            'openid' => $openid,
            'unionid' => $unionid,
            'bind_type' => $bindType,
            'action' => $action,
            'ip' => request()->ip(),
            'user_agent' => request()->header('User-Agent'),
            'status' => 1,
            'message' => $message,
            'createtime' => time()
        ];
        
        Db::name('wechat_bind_log')->insert($logData);
    }

    /**
     * 获取用户绑定状态
     */
    public static function getUserBindStatus($userId)
    {
        $user = User::find($userId);
        if (!$user) {
            return false;
        }
        
        return [
            'is_bound' => !empty($user->wechat_openid),
            'openid' => $user->wechat_openid,
            'unionid' => $user->wechat_unionid,
            'bind_time' => $user->bind_time,
            'wechat_nickname' => $user->wechat_nickname,
            'wechat_avatar' => $user->wechat_avatar
        ];
    }

    /**
     * 获取管理员绑定状态
     */
    public static function getAdminBindStatus($adminId)
    {
        $admin = AdminModel::find($adminId);
        if (!$admin) {
            return false;
        }
        
        return [
            'is_bound' => !empty($admin->wechat_openid),
            'openid' => $admin->wechat_openid,
            'unionid' => $admin->wechat_unionid,
            'bind_time' => $admin->bind_time,
            'wechat_nickname' => $admin->wechat_nickname,
            'wechat_avatar' => $admin->wechat_avatar
        ];
    }

    /**
     * 同步微信用户信息
     */
    public static function syncWechatUserInfo($userId, $userInfo)
    {
        $user = User::find($userId);
        if (!$user) {
            throw new Exception('用户不存在');
        }
        
        $updateData = [];
        
        // 更新微信相关信息
        if (!empty($userInfo['nickName'])) {
            $updateData['wechat_nickname'] = $userInfo['nickName'];
        }
        if (!empty($userInfo['avatarUrl'])) {
            $updateData['wechat_avatar'] = $userInfo['avatarUrl'];
        }
        
        // 如果用户昵称或头像为空，使用微信信息
        if (!empty($userInfo['nickName']) && (empty($user->nickname) || $user->nickname === $user->username)) {
            $updateData['nickname'] = $userInfo['nickName'];
        }
        if (!empty($userInfo['avatarUrl']) && empty($user->avatar)) {
            $updateData['avatar'] = $userInfo['avatarUrl'];
        }
        
        if (!empty($updateData)) {
            $user->save($updateData);
        }
        
        return $user;
    }

    /**
     * 获取未绑定的用户列表
     */
    public static function getUnboundUsers($keyword = '', $page = 1, $limit = 10)
    {
        $where = [['wechat_openid', '=', '']];
        
        if (!empty($keyword)) {
            $where[] = ['username|nickname|mobile|email', 'like', "%{$keyword}%"];
        }
        
        return User::where($where)
            ->field('id,username,nickname,mobile,email,createtime')
            ->order('id desc')
            ->paginate($limit, false, ['page' => $page]);
    }

    /**
     * 获取未绑定的管理员列表
     */
    public static function getUnboundAdmins($keyword = '', $page = 1, $limit = 10)
    {
        $where = [['wechat_openid', '=', '']];
        
        if (!empty($keyword)) {
            $where[] = ['username|nickname', 'like', "%{$keyword}%"];
        }
        
        return AdminModel::where($where)
            ->field('id,username,nickname,email,createtime')
            ->order('id desc')
            ->paginate($limit, false, ['page' => $page]);
    }
}
